/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { ArkFile, ts } from 'arkanalyzer';

import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Defects } from '../../Index';
import { AstMatcher, MatcherCallback, MatcherTypes } from '../../Index';
import { Rule } from '../../Index';
import { RuleListUtil } from '../../utils/common/DefectsList';
import { IssueReport } from '../../model/Defects';
import { CheckerUtils } from '../../utils/checker/CheckerUtils';


const gMetaData: BaseMetaData = {
    severity: 2,
    ruleDocPath: 'docs/no-this-alias.md',
    description: 'Disallow aliasing this.'
};

type Options = [{
    allowDestructuring: boolean,
    allowedNames: string[]
}]

export class NoThisAliasCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    private allowDestructuring = true;
    private allowedNames: string[] = [];
    public issues: IssueReport[] = [];
    private processedFiles: Set<string> = new Set();

    // Simplified AST Matchers using factory method
    private createMatcher = (predicate: (node: ts.Node) => boolean): AstMatcher => ({
        matcherType: MatcherTypes.AST,
        match: predicate
    });

    private readonly matchers = {
        variableDeclaration: this.createMatcher(ts.isVariableDeclaration),
        binaryExpression: this.createMatcher(ts.isBinaryExpression)
    };

    public registerMatchers(): MatcherCallback[] {
        return [
            { matcher: this.matchers.variableDeclaration, callback: this.checkVariableDeclarationNode },
            { matcher: this.matchers.binaryExpression, callback: this.checkBinaryExpressionNode }
        ];
    }

    // Required by BaseChecker interface
    public check = (_targetFile: ArkFile): void => {
        this.initializeRuleOptions();
    };

    // Unified method to handle all common checks and initialization
    private prepareFileForProcessing(targetFile: ArkFile): boolean {
        if (!CheckerUtils.shouldProcessFile(targetFile, ['.ts'])) {
            return false;
        }

        const filePath = targetFile.getFilePath();
        if (!this.processedFiles.has(filePath)) {
            this.processedFiles.add(filePath);
        }

        return true;
    }

    private initializeRuleOptions(): void {
        const options = this.rule?.option as Options;
        if (options?.length > 0) {
            const option = options[0];
            this.allowDestructuring = option.allowDestructuring ?? this.allowDestructuring;
            this.allowedNames = option.allowedNames ?? this.allowedNames;
        }
    }

    private reportIssueAtNode(sourceFile: ts.SourceFileLike, node: ts.Node, targetFile: ArkFile, message: string): void {
        const position = CheckerUtils.getNodePosition(sourceFile, node);
        this.addIssueReport(targetFile, position.line, position.column, 0, message);
    }

    // Generic callback creator to reduce repetition
    private createCallback = <T extends ts.Node>(
        predicate: (node: ts.Node) => node is T
    ) => (node: ts.Node, targetFile: ArkFile): void => {
        if (!this.prepareFileForProcessing(targetFile)) {
            return;
        }

        // Inline AstMatcherUtils.processAstNode
        const result = CheckerUtils.processNodeWithSourceFile(node, targetFile, (sourceFile: ts.SourceFile, node: ts.Node, targetFile: ArkFile) => {
            if (predicate(node)) {
                this.checkThisAlias(targetFile, sourceFile, node);
            }
        });
        if (result === null) {
            // 如果处理失败，抛出错误以保持原有行为
            throw new Error('Failed to process node with source file');
        }
    };

    // AST Matcher callback methods
    public checkVariableDeclarationNode = this.createCallback(ts.isVariableDeclaration);
    public checkBinaryExpressionNode = this.createCallback(ts.isBinaryExpression);

    private checkThisAlias(targetFile: ArkFile, sourceFile: ts.SourceFileLike, aNode: ts.Node): void {
        const children = aNode.getChildren();
        if (children.length === 0 || children[children.length - 1].kind !== ts.SyntaxKind.ThisKeyword) {
            return;
        }

        const firstNode = children[0];
        const message = this.getAliasMessage(firstNode);

        if (message) {
            this.reportIssueAtNode(sourceFile, firstNode, targetFile, message);
        }
    }

    private getAliasMessage(firstNode: ts.Node): string | undefined {
        if (ts.isObjectBindingPattern(firstNode) || ts.isArrayBindingPattern(firstNode)) {
            return this.allowDestructuring ? undefined : 'Unexpected aliasing of members of \'this\' to local variables.';
        }

        const name = firstNode.getText();
        return this.allowedNames.includes(name) ? undefined : 'Unexpected aliasing of \'this\' to local variable.';
    }

    private addIssueReport(arkFile: ArkFile, line: number, startCol: number, endCol: number, message: string): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        const filePath = arkFile.getFilePath();
        const defect = new Defects(line, startCol, endCol, message, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }
}